package cn.wit.summit.chwan.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bigkoo.convenientbanner.ConvenientBanner;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.GameListAdapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.response.GameLibraryV3Response;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/9/7.
 */

public class GameListFragment extends BaseFragment {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private int pn = 1;
    private int typeId;
    private GameListAdapter adapter;
    private List<GameListAdapter.ViewBean> viewBeans = new ArrayList<>();
    private LinearLayoutManager layoutManager;

    public static GameListFragment newInstance(int typeId) {
        GameListFragment temp = new GameListFragment();
        temp.typeId = typeId;
        return temp;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_game_library_one, container, false);
        ButterKnife.bind(this, view);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        adapter = new GameListAdapter(getActivity(), viewBeans);
        layoutManager = new LinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return true;
            }
        };
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getIndexDataForFirst();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getIndexData();
            }
        });

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);//订阅
        }
        getIndexDataForFirst();
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getActivity()!=null && isVisibleToUser) {
        }
    }

    private void getIndexDataForFirst() {
        pn = 1;
        getIndexData();
    }

    private void getIndexData() {
        api.getGameRankingV3(retrofitManager.gameRankingV3Request(pn, typeId)).enqueue(new MyCallback<ResponseBase<List<GameListBaseBean>>>() {
            @Override
            public void onSuccess(ResponseBase<List<GameListBaseBean>> model) {
                List<GameListBaseBean> data = model.getData_info();
                if (data != null) {
                    updataUi(data);
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                showToast(msg);
                if (refreshLayout!=null)
                    refreshLayout.finishLoadMore();
            }
        });
    }

    private void updataUi(List<GameListBaseBean> data) {
        if (data == null) {
            return;
        }
        int po = 0;
        if (pn == 1) {
            viewBeans.clear();
        } else {
            po = viewBeans.size();
        }

        for (int i = 0; data != null && i < data.size(); i++) {
            GameListBaseBean temp = data.get(i);
            GameListAdapter.ViewBean viewBean = new GameListAdapter.ViewBean(GameListAdapter.ViewType.TYPE_ITEM, temp);
            viewBeans.add(viewBean);
        }

        adapter.notifyItemRangeChanged(po, viewBeans.size());
        if (refreshLayout != null) {
            if (pn != 1 && (data == null || data.size() == 0)) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                if (pn == 1)
                    refreshLayout.finishRefresh();
                else
                    refreshLayout.finishLoadMore();
                pn += 1;
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(DownloadEvent downloadEvent) {
        String str = adapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View view = layoutManager.findViewByPosition(Integer.valueOf(str));
            ItemListView itemView = view.findViewById(R.id.listItem);
            if (itemView == null) {
                return;
            }
            DownloadViewStroke dowView = itemView.getDownView();
            dowView.updateButn(table);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//订阅
    }
}
